package com.jiuzhou.guanwang.jzcp.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jiuzhou.guanwang.jzcp.R;
import com.jiuzhou.guanwang.jzcp.activity.CusWebActivity;
import com.jiuzhou.guanwang.jzcp.adapter.NewsAdapter;
import com.jiuzhou.guanwang.jzcp.base.DefaultAdapter;
import com.jiuzhou.guanwang.jzcp.bean.NewsResult;
import com.jiuzhou.guanwang.jzcp.netutil.NetRequestUtil;
import com.jiuzhou.guanwang.jzcp.utils.TimeUtil;
import com.jiuzhou.guanwang.jzcp.widget.RecycleViewDivider;
import com.vise.log.ViseLog;

import org.xutils.common.Callback;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class NewsFragment extends Fragment {
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.title)
    TextView tvTitle;
    Unbinder unbinder;
    private View rootView;
    private List<NewsResult> data = new ArrayList<>();
    private NewsAdapter newsAdapter;
    public static NewsFragment newInstance(String info) {
        Bundle args = new Bundle();
        NewsFragment fragment = new NewsFragment();
        args.putString("info", info);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            String name = bundle.get("info").toString();
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_expert, null);
            unbinder = ButterKnife.bind(this, rootView);
            initView();
            initData();
        } else {
            // 缓存的rootView需要判断是否已经被加过parent，如果有parent需要从parent删除，
            // 要不然会发生这个rootview已经有parent的错误。
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
        }


        return rootView;
    }

    private void initView() {
        tvTitle.setText("新闻资讯");
        newsAdapter = new NewsAdapter(getActivity(), data);
        recyclerView.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.VERTICAL, 1, getResources().getColor(R.color.divider_list)));
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(newsAdapter);
        newsAdapter.setOnItemClickListener(new DefaultAdapter.OnItemClickListener<NewsResult>() {
            @Override
            public void onClick(View view, RecyclerView.ViewHolder holder, NewsResult o, int position) {
                Intent intent = new Intent(getActivity(), CusWebActivity.class);
                intent.putExtra("url" ,o.getUrl());
                startActivity(intent);

            }
        });
    }

    private void jumpToDetail(String s) {
//        Intent intent = new Intent(getActivity(), ExpDetailActivity.class);
//        intent.putExtra("userId", s);
//        startActivity(intent);
    }


    protected void initData() {
        Map<String, String> map = new HashMap<>();
        String time = TimeUtil.getDateTimeFromMillisecond(System.currentTimeMillis());
        map.put("cfrom", "ios");
        map.put("channel", "159cpgfbios");
        map.put("version", "1");
        Callback.Cancelable post = NetRequestUtil.getInstance().get("https://smapi.159cai.com/discovery/news/szc/index.json", map, 101,
                new NetRequestUtil.NetResponseListener<String>() {
                    @Override
                    public void onSuccess(String response, int requestCode) {
                        ViseLog.d(response);

                        Type type = new TypeToken<List<NewsResult>>() {
                        }.getType();
                        List<NewsResult> beanOnes = new Gson().fromJson(response, type);
                        data.addAll(beanOnes);
                        newsAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFailed(String response, int requestCode) {
                        ViseLog.e("请求失败");
                        showToast("返回失败");
                    }

                    @Override
                    public void onError(Throwable e) {
                        showToast("返回解析异常");
                    }

                    @Override
                    public void onFinished() {
                    }
                });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
    public void showToast(String text) {
        Toast.makeText(getActivity(), "" + text, Toast.LENGTH_SHORT).show();
    }

    public void showToast(int resId) {
        Toast.makeText(getActivity(), this.getResources().getText(resId), Toast.LENGTH_SHORT).show();
    }

}
